const http = require('http');
const fs = require('fs');
const path = require('path');

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    // 只处理根路径请求
    if (req.url === '/' && req.method === 'GET') {
        // 读取图片文件并转换为Base64
        // 注意：这里假设图片文件与bufferImg.js在同一目录下
        // 实际使用时请替换为你的图片路径
        const imagePath = path.join(__dirname, 'book.jpg');
        
        fs.readFile(imagePath, (err, data) => {
            if (err) {
                res.writeHead(500, { 'Content-Type': 'text/plain' });
                res.end('服务器错误：无法读取图片文件');
                return;
            }
            
            // 将图片Buffer转换为Base64编码
            const base64Image = data.toString('base64');
            const imageSrc = `data:image/jpeg;base64,${base64Image}`;
            
            // 构建HTML响应内容
            const html = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>Node.js图片展示</title>
                <style>
                    body { 
                        display: flex; 
                        justify-content: center; 
                        align-items: center; 
                        min-height: 100vh; 
                        margin: 0; 
                        background-color: #f0f0f0;
                    }
                    .book-container {
                        padding: 20px;
                        background-color: white;
                        border-radius: 8px;
                        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    }
                    .book-image {
                        max-width: 100%;
                        height: auto;
                    }
                </style>
            </head>
            <body>
                <div class="book-container">
                    <img src="${imageSrc}" alt="深入浅出Node.js书籍封面" class="book-image">
                </div>
            </body>
            </html>
            `;
            
            // 发送HTML响应
            res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end(html);
        });
    } else {
        // 处理其他路径请求
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 页面未找到');
    }
});

// 监听8081端口
const port = 8081;
server.listen(port, () => {
    console.log(`服务器已启动，正在监听端口 ${port}`);
    console.log(`请访问 http://localhost:${port}`);
});
